package vip.xiaonuo.common.util;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 通用文件操作工具类
 */
public class CommonFileUtil {

    /**
     * 导出zip
     * @param srcFiles
     * @param outputZipFilePath
     * @return
     */
    public static Path compressFilesToZip(List<File> srcFiles, String outputZipFilePath) {
        Path destZipPath = Paths.get(outputZipFilePath);

        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(destZipPath.toFile()))) {
            for (File srcFile : srcFiles) {
                if (!srcFile.exists()) {
                    System.err.println("Warning: Skipping non-existent file " + srcFile.getAbsolutePath());
                    continue;
                }

                // 将文件添加到压缩包
                ZipEntry zipEntry = new ZipEntry(srcFile.getName());
                zipEntry.setSize(srcFile.length()); // 设置原始文件大小
                zipEntry.setTime(srcFile.lastModified()); // 保持原文件最后修改时间

                zipOut.putNextEntry(zipEntry);

                try (FileInputStream fis = new FileInputStream(srcFile)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) >= 0) {
                        zipOut.write(buffer, 0, length);
                    }
                }

                zipOut.closeEntry(); // 关闭当前条目
            }

            System.out.println("Successfully compressed files into " + destZipPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return destZipPath;
    }
}